package stu

import (
	"code.oldboyedu.com/studygo/ginStsMgr/common"
	"code.oldboyedu.com/studygo/ginStsMgr/dao/init_mysql"
	"code.oldboyedu.com/studygo/ginStsMgr/model"
)

/*
	学生的sql增删改查
*/
func CheckName(name string) int {
	var names model.Student
	init_mysql.Db.Select("id").Where("name=?", name).First(&names)
	if names.ID > 0 {
		return common.StuNameExist
	}
	return common.SUCCESS

}

// CheckId 查看单个学生信心时使用id来判断
func CheckId(id int, data *model.Student) int {
	err := init_mysql.Db.Where("id=?", id).First(&data).Error
	if err != nil {
		return common.ERROR
	}
	return common.SUCCESS
}
func CreateStu(data *model.Student) int {
	err := init_mysql.Db.Create(&data).Error
	if err != nil {
		return common.CreateStuFailed
	}
	return common.SUCCESS
}
func ViewStu(pagesize, pagenum int) ([]model.Student, int) {
	var stuList []model.Student
	err := init_mysql.Db.Limit(pagesize).Offset((pagenum - 1) * pagesize).Preload("Teacher").Preload("Subject").Find(&stuList).Error
	if err != nil {
		return nil, common.ViesStuFailed
	}
	return stuList, common.SUCCESS
}
func ViewStuId(id int) int {
	var stuList model.Student
	//
	err := init_mysql.Db.Where("id=?", id).Preload("Teacher").Preload("Subject").Find(&stuList).Error
	if err != nil {
		return common.ERROR
	}
	return common.SUCCESS
}
func UpdateStu(id int, data *model.Student) int {
	//var stuList model.Student
	//var maps = make(map[string]interface{})
	////maps["name"] = data.Name
	//maps["age"] = data.Age
	//maps["subject"] = data.Subject
	//err := init_mysql.Db.Model(&stuList).Where("id=?", id).Updates(maps).Error
	//if err != nil {
	//	return common.UpdateStuFailed
	//}
	//return common.SUCCESS
	var stuList model.Student
	err := init_mysql.Db.First(&stuList, id).Error
	if err != nil {
		return common.ERROR
	}

	tx := init_mysql.Db.Begin()
	// 更新基本信息
	if err := tx.Model(&stuList).Updates(data).Error; err != nil {
		tx.Rollback()
		return common.UpdateStuFailed
	}

	// 更新关联信息
	if data.Teacher != nil {
		if err := tx.Model(&stuList).Association("Teacher").Replace(data.Teacher).Error; err != nil {
			tx.Rollback()
			return common.UpdateStuFailed
		}
	}
	if data.Subject != nil {
		if err := tx.Model(&stuList).Association("Subject").Replace(data.Subject).Error; err != nil {
			tx.Rollback()
			return common.UpdateStuFailed
		}
	}

	tx.Commit()
	init_mysql.Db.Model(&stuList).Related(&stuList.ClassID)
	init_mysql.Db.Model(&stuList).Association("Teacher").Find(&stuList.Teacher)
	init_mysql.Db.Model(&stuList).Association("Subject").Find(&stuList.Subject)
	return common.SUCCESS
}
func DelStu(id int, data *model.Student) int {
	err := init_mysql.Db.Where("id=?", id).Delete(&data)
	if err != nil {
		return common.DelStuFailed
	}
	return common.SUCCESS
}
